
<?php
class SendTaskMail{
			
	private $mail_cacheuid;

	function __construct($arr){

		//$this->mail_cacheuid = "/home/mail/l/a/l/domains/lala.com/";

		@extract($arr);

		$sql = @mysql_connect($CFG_MYSQL_HOST, $CFG_MYSQL_USER, $CFG_MYSQL_PASS);
		@mysql_select_db($CFG_MYSQL_DB,$sql);

	}


	/**

	 *@author     liuchaoqun 

	 *@parameter	 

	 *@return     所有待发送的数组     $result  

	 *@date       2013/8/19

	 **/


		
    private function GetEmail(){

        //执行脚本的时间

        $start_time = date("Y-m-d H:i:s",time());

        $now_ymd = date("Y-m-d",time());
        //执行脚本的时间加5分钟的时间

        $now_i = intval(date("i",time()));

        $now_h = intval(date("H",time()));
        if($now_i == 60){

            $new_h =  strval($now_h+=1);

            $where_time =date("Y-m-d H:i:s",strtotime( $now_ymd." ".$new_h.":00".":00"));

        }else{
            if(($now_i+5)>=60){
                $now_h +=1;
                $now_i -=60;
            }
            $new_i = strval($now_i+=5);
            if($new_i<10){
                $new_i = "0".$new_i;
            }
            $new_h = strval($now_h);
            $strtime =  $now_ymd." ".$new_h.":".$new_i.":00";
            $where_time =date("Y-m-d H:i:s",strtotime( $now_ymd." ".$new_h.":".$new_i.":00"));
        }

	$sql = "SELECT Id,Email,SendTime,SetTime,Pid,Status,UserPath FROM AutoSend WHERE SendTime>='".$start_time ."' AND SendTime<='".$where_time."' AND Status = 0";
        $query = @mysql_query($sql);
        $result = array();
        while ($row = @mysql_fetch_array($query,MYSQL_ASSOC)) {

            $result[] = $row;

        }

        return $result;

    }



	/**

	 *@author liuchaoqun 

	 *@parameter    发送成功的邮件id     $email_id

	 *@return       

	 *@date     2013/8/19

	 **/

	private function UpEmailStatus($email_id){
		echo $email_id;
		$sql = "UPDATE `webmail`.`AutoSend` SET `Status` = '1' WHERE `AutoSend`.`Id` =".$email_id." LIMIT 1 ;";

		$query = @mysql_query($sql);

	}
												
	/**
	*@parameter 获取域地址
	*
	*
	*/

	private function GetDomainPath($path){
		$userpath = explode("/",$path);
		array_shift($userpath);
		array_pop($userpath);
		$numb = count($userpath);
		$upath = "";
		for($i= 0; $i<$numb;$i++){
			$upath .= "/".$userpath[$i];
			
		}
		
		return $upath;
	}

	/**

	 *@author liuchaoqun 

	 *@function		获取定时发送的邮件铭文                  GetInscriptions

	 *@parameter     所有定时发送的数组						$result

	 *@return		返回所有定时发送邮件铭文的文件名		$ins_path

	 *@date     2013/8/20

	 **/

		private function GetInscriptionsPath($result){
			if(is_array($result)){
 
				$ins_path = array();
				foreach($result as $key=>$em){
					$emailarr = $this->GetInscriptionsFile($em["UserPath"]);
					$user_path = $this->GetDomainPath($em["UserPath"]);
					$this->mail_cacheuid = $user_path;
					foreach($emailarr as $ke=>$einfo){
						$emailinfo = explode(".",$einfo);
						if($emailinfo[1] == $em["Pid"]){

							$person_path = explode("@",$em["Email"]);

							$ins_path[$ke]["EmailId"]  = $em["Id"];

							$ins_path[$ke]["mail_sender"]= $em["Email"];
							
							
							$ins_path[$ke]["mail_cacheuid"] = $this->mail_cacheuid."/".$person_path[0]."/cachedir";

							//$ins_path[$ke]["mail_path"] = $em["UserPath"]."/Maildir/.Draft/cur/";

							$ins_path[$ke]["mail_path"] = $em["UserPath"]."/Maildir/.&g0l6Pw-/cur/";
							
							$ins_path[$ke]["mail_file"] = $einfo;

							//$ins_path[$ke]["move_path"] = $em["UserPath"]."/Maildir/.Sent/cur/";
							$ins_path[$ke]["move_path"] = $em["UserPath"]."/Maildir/.&XfJT0ZABkK5O9g-/cur/";


						}

					}

				}
			return $ins_path;

		}

		}
		/**

		 *@author liuchaoqun 

		 *@function		获取定时发送的邮件铭文的文件名          GetInscriptionsFile

		 *@parameter     该用户的$UserPath

		 *@return		返回所有定时发送邮件铭文的文件名		$emailarr

		 *@date     2013/8/20

		 **/

		public function GetInscriptionsFile($userpath){


			//$filepath = $userpath."/Maildir/.Draft/cur";
			$filepathcur = $userpath."/Maildir/.&g0l6Pw-/cur";
			$filepathnew = $userpath."/Maildir/.&g0l6Pw-/new";
			$emailarr = array();

			if ( $handle = opendir($filepathcur) ) {

				while ( ($file = readdir($handle)) !== false ) {

					if($file != ".." && $file != "."){

						$emailarr[] = $file;

					}

				}

			}
			closedir($handle);
			if ( $handlenew = opendir($filepathnew) ) { 
                                 while ( ($file = readdir($handlenew)) !== false ) {

                                         if($file != ".." && $file != "."){
 
                                                 $emailarr[] = $file.'#new';
 
                                         }
 
                                }

                         }
			 closedir($handlenew);

			return $emailarr;

		}

		/**

		 *@author liuchaoqun 

		 *@function		修改文件名，并把文件移动到发件箱          sendmail_end

		 *@parameter     该用户的$UserPath

		 *@return		返回所有定时发送邮件铭文的文件名		$emailarr

		 *@date     2013/8/20

		 **/

		private function sendmail_end($mail_dir,$new_dir){
			

			$re_name = rename($mail_dir,$new_dir);

			$de_file = @unlink($mail_dir);

		}


		
		/**

		 *@author    liuchaoqun 

		 *@parameter

		 *@return   

		 *@date     2013/8/19

		 **/

		public function send(){

			//从数据库获取所有定时发送的数组

			$task_email   = $this->GetEmail();
			//获取所有邮件铭文的数组
			$Inscriptions = $this->GetInscriptionsPath($task_email);
			//遍历数组发送邮件
			foreach($Inscriptions as $ke=>$se_m){
				@extract($se_m);
				
				//判断是在cur或者是new目录
				$judge_dir = explode('#new',$mail_file);
				if(isset($judge_dir[1])){ 	//存在说明是new目录下
					$mail_path = str_replace('cur','new',$mail_path);
					$mail_file = $judge_dir[0];
				}
		
				//源文件
				$mail_dir= $mail_path.$mail_file;
			 	$send_mail = $this->SendEmail($mail_sender,$mail_cacheuid,$mail_dir);

				//如果成功修改文件名，数据库status状态，移动文件到发件箱目录

				if($send_mail==0){

					$email_info = explode(".",$mail_file);


					$new_name = $email_info[0].".".$email_info[1].".".$email_info[3].".".$email_info[4].".".$email_info[5];

					//要移动的文件


					$new_dir = $move_path.$new_name;
					$this->UpEmailStatus($EmailId);
					$this->sendmail_end($mail_dir,$new_dir);

				}

			}



		}


		
		/**

		 *@author liuchaoqun 

		 *@parameter 

		 *	       发件人邮箱           $mail_sender 

		 *	       发送邮件的木板路径   $mail_cacheuid

		 *	       加密后的邮件原文     $mail_dir

		 *@return   

		 *          邮件发送状态         $iRetVal 

		 *@date     2013/8/19

		 **/

		private function SendEmail($mail_sender,$mail_cacheuid,$mail_dir){

			$mailFileText = '';

			//打开邮件的原文 文件取出 内容 赋值给 $mailFileText

			$fp = @fopen($mail_dir,"r");

			if( $fp ){

				$mailFileText = @fread($fp,60*1024);

				if( empty($mailFileText) ) $mailFileText = "";

				@fclose($fp);

			}

			//创建发送邮件的临时模版

			$tmpFileNamePrefix = "sendmail_". time() . "_";

			$tmpFileName = tempnam($mail_cacheuid, $tmpFileNamePrefix);



			//将 $mailFileText 写入到临时模板

			$mailFile = @fopen($mail_cacheuid."/".basename($tmpFileName), "w");

			@fputs($mailFile, $mailFileText, strlen($mailFileText));

			@fclose($mailFile);


			
			//调用外部文件 sendmail 返回$iRetVal 并删除临时模板

			$sendCmd  = "/usr/sbin/sendmail -t -i -f ";

			$sendCmd .= $mail_sender;

			$sendCmd .= "< ".$tmpFileName;

			@system($sendCmd, $iRetVal);

			@unlink($tmpFileName);

			return $iRetVal;

		}

	}


$arr = Array(

		"CFG_MYSQL_HOST" => "127.0.0.1",

		"CFG_MYSQL_USER" => "web_rwuser",

		"CFG_MYSQL_PASS" => "Gweb8zhY",

		"CFG_MYSQL_DB" => "webmail"
																   );

$send = new SendTaskMail($arr);

$send->send();

?>
